package cn.anoxia.springframework.aop.framework;

import cn.anoxia.springframework.aop.AdvisedSupport;
import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * The class JdkDynamicAopProxy.
 * <p>
 * Description:
 *
 * @author: huangle
 * @since: 2021/08/31 9:44
 */
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

  private final AdvisedSupport advisedSupport;

  public JdkDynamicAopProxy(AdvisedSupport advisedSupport){
    this.advisedSupport = advisedSupport;
  }


  @Override
  public Object getProxy() {
    return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),advisedSupport.getTargetSource().getTargetClass(),this);
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (advisedSupport.getMethodMatcher().matches(method,advisedSupport.getTargetSource().getTarget().getClass())){
      // 获取方法拦截器
      MethodInterceptor methodInterceptor = advisedSupport.getMethodInterceptor();
      // 初始化
      return methodInterceptor.invoke(new ReflectiveMethodInvocation(advisedSupport.getTargetSource().getTarget(), method, args));
    }

    return method.invoke(advisedSupport.getTargetSource().getTarget(),args);
  }
}
